package org.gikolet.ch2.android.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.gikolet.ch2.data.Board;
import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.io.Parser;
import org.gikolet.ch2.io.ThreadHeadersReader;

public class Ch2ThreadHeadersReader implements ThreadHeadersReader {

	private static final Parser<ThreadHeader> parser = new Ch2ThreadHeaderPAF();

	private Board board;
	private HttpURLConnection http;
	private BufferedReader reader;

	public Ch2ThreadHeadersReader(Board board) throws IOException {

		URL url = new URL("http://" + board.getHostName() + "/"
				+ board.getPath() + "/subject.txt");

		this.board = board;
		this.http = (HttpURLConnection) url.openConnection();

		this.http.setRequestMethod("GET");
		this.http.connect();

		this.reader = new BufferedReader(new InputStreamReader(this.http
				.getInputStream(), "MS932"));
	}

	public ThreadHeader read() throws IOException {
		String line = this.reader.readLine();

		if (line == null) {
			return null;
		}

		ThreadHeader s = parser.parse(line);
		s.setBoard(this.board);

		return s;
	}

	public void close() throws IOException {
		try {
			this.reader.close();

		} finally {
			this.http.disconnect();
		}
	}
}
